﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Util
{
    public class ConfigurationUtil
    {
        private static Dictionary<string, string> configData = new Dictionary<string, string>();

        public static void LoadConfig(string filePath)
        {
            using (StreamReader file = new StreamReader(filePath))
            {
                if (!file.BaseStream.CanRead)
                {
                    Console.WriteLine("Error opening file: " + filePath);
                    return;
                }

                string line;
                while ((line = file.ReadLine()) != null)
                {
                    // 忽略注释和空行
                    if (string.IsNullOrEmpty(line) || line[0] == '#')
                    {
                        continue;
                    }

                    // 查找等号，解析键值对
                    int delimiterPos = line.IndexOf('=');
                    if (delimiterPos == -1)
                    {
                        Console.WriteLine("Invalid line: " + line);
                        continue;
                    }

                    // 提取键值对
                    string key = line.Substring(0, delimiterPos);
                    string value = line.Substring(delimiterPos + 1);

                    // 移除键值对两端的空格
                    key = key.Trim();
                    value = value.Trim();

                    // 添加到配置
                    configData[key] = value;
                }
            }
        }

        public static T GetConfigValue<T>(string key)
        {
            if (configData.ContainsKey(key))
            {
                return (T)Convert.ChangeType(configData[key], typeof(T));
            }
            return default(T);
        }
    }
}
